package com.sanjiahantang.ythshopping.http;

import com.sanjiahantang.ythshopping.model.UploadImage;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/6/28.
 */

public  class HttpFormClient {
    static String multipart_form_data = "multipart/form-data";
    static String twoHyphens = "--";
    static String boundary = "****************fD4fH3gL0hK7aI6";    // 数据分隔符
    static String lineEnd = System.getProperty("line.separator");    // The value is "\r\n" in Windows.
    /*
   * 构建表单字段内容，格式请参考HTTP 协议格式（用FireBug可以抓取到相关数据）。(以便上传表单相对应的参数值)
   * 格式如下所示：
   * --****************fD4fH3hK7aI6
   * Content-Disposition: form-data; name="action"
   * // 一空行，必须有
   * upload
   */
    private static StringBuilder addFormField(Map<String,Object> params, DataOutputStream output) throws Exception{
        StringBuilder sb = new StringBuilder();

        Iterator it=params.keySet().iterator();
        while(it.hasNext()){
            String key=it.next().toString();
            sb.append(twoHyphens + boundary + lineEnd);
            sb.append("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
            sb.append(lineEnd);
            sb.append(params.get(key).toString()+ lineEnd);
        }

        return sb;

//        try {
//            output.writeBytes(sb.toString());// 发送表单字段数据
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }

    public static String Frompost (String actionUrl, Map<String,Object> params, List<UploadImage> bytes) throws Exception{
        HttpURLConnection conn = null;
        DataOutputStream output = null;
        BufferedReader input = null;
        try {
            URL url = new URL(actionUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(120000);
            conn.setDoInput(true);        // 允许输入
            conn.setDoOutput(true);        // 允许输出
            conn.setUseCaches(false);    // 不使用Cache
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);

            conn.connect();
            output = new DataOutputStream(conn.getOutputStream());

            StringBuilder sb = addFormField(params, output);// 添加表单字段内容

            output.write(sb.toString().getBytes());

            for (int i = 0; i < bytes.size(); i ++ ){
                output.writeBytes(twoHyphens + boundary + lineEnd);
                output.writeBytes("Content-Disposition: form-data; name=\"" +  "shaidan_img" + (i + 1)+".jpg" + "\"" + ";filename=\""
                        + "shaidan_img" + (i + 1)+".jpg"
                        + "\"" + lineEnd);
                output.writeBytes(lineEnd);
                output.write(bytes.get(i).getData());
                output.writeBytes(lineEnd);

            }
            output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // 数据结束标志
            output.flush();

            int code = conn.getResponseCode();
            if(code != 200) {
                throw new RuntimeException("请求‘" + actionUrl +"’失败！");
            }

            input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String oneLine;
            while((oneLine = input.readLine()) != null) {
                response.append(oneLine + lineEnd);
            }

            return response.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 统一释放资源
            try {
                if(output != null) {
                    output.close();
                }
                if(input != null) {
                    input.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            if(conn != null) {
                conn.disconnect();
            }
        }
    }

}
